package com.ant.androiddemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MutiThreadHandlerActivity extends AppCompatActivity {
    private TextView tvContent;
    String strFromNet;



    private Handler mHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (msg.what == 0) {
                String strData = (String) msg.obj;
                tvContent.setText(strData);

                Toast.makeText(MutiThreadHandlerActivity.this,"主线程收到消息啦！",Toast.LENGTH_SHORT).show();
            }

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_muti_thread_handler);
        tvContent = findViewById(R.id.tv_content);
    }

    public void start(View view) {

        // 做一个耗时任务
        new Thread(new Runnable() {
            @Override
            public void run() {
                String stringFromNet = getStringFromNet();

                Message message = new Message();
                message.what = 0;
                message.obj = stringFromNet;

                mHandler.sendMessage(message);

            }
        }).start();

        Toast.makeText(this,"任务完成！",Toast.LENGTH_SHORT).show();

    }

    private String getStringFromNet() {
        // 假装从网络获取了一个字符串
        String result = "";

        StringBuilder stringBuilder = new StringBuilder();

        // 模拟一个耗时操作
        for (int i = 0; i < 100; i++) {
            stringBuilder.append("字符串" + i);
        }

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        result = stringBuilder.toString();

        return result;
    }
}